<template>
    <div>
      <!--      面包屑导航区域-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>参数列表</el-breadcrumb-item>
      </el-breadcrumb>
<!--    卡片视图-->
      <el-card>
<!--        警告区域-->
        <el-alert
          title="注意：只允许为第三级分类设置相关参数"
          type="warning"
          show-icon>
        </el-alert>
<!--        选择商品分类-->
        <el-row class="cat_opt">
          <el-col>
            <span>选择商品分类：</span>
<!--            选择商品分类级联选择框-->
            <el-cascader
              v-model="selectedCateKeys"
              :options="cateList"
              :props="cateProps"
              @change="handleChange"></el-cascader>
          </el-col>
        </el-row>
<!--        tab标签-->
        <el-tabs v-model="activeName" @tab-click="handleClick">
<!--          动态参数面板-->
          <el-tab-pane label="动态参数" name="many">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
<!--            动态表格区域-->
            <el-table :data="manyTableData" border stripe>
<!--              展开行-->
              <el-table-column type="expand">
                <template slot-scope="scope">
<!--                  循环渲染的tag标签-->
                  <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable
                  @close="handleClosed(i,scope.row)">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
<!--              索引列-->
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="参数名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="showDeleteDialog(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
<!--          静态属性面板-->
          <el-tab-pane label="静态属性" name="only">
            <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
<!--            静态参数-->
            <el-table :data="onlyTableData" border stripe>
<!--              展开行-->
              <el-table-column type="expand">
                <template slot-scope="scope">
                  <!--                  循环渲染的tag标签-->
                  <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable
                          @close="handleClosed(i,scope.row)">{{item}}</el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </template>
              </el-table-column>
              <el-table-column type="index" label="#"></el-table-column>
              <el-table-column prop="attr_name" label="属性名称"></el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" icon="el-icon-delete" size="mini" @click="showDeleteDialog(scope.row.attr_id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-card>
<!--      添加参数对话框-->
      <el-dialog
        :title="'添加'+ titleText"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed">
        <el-form :model="addRuleForm" :rules="addRuleFormRules" ref="addRuleFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addRuleForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
<!--      修改参数对话框-->
      <el-dialog
        :title="'修改'+ titleText"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed">
        <el-form :model="editRuleForm" :rules="editRuleFormRules" ref="editRuleFormRef" label-width="100px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editRuleForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </div>
</template>

<script>
export default {
  name: 'Params',
  data () {
    return {
      // 商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cateProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择框双向绑定的数组
      selectedCateKeys: [],
      // 被激活的tab页签名称
      activeName: 'many',
      // 动态参数数据
      manyTableData: [],
      // 静态属性数据
      onlyTableData: [],
      // 添加对话框的默认关闭
      addDialogVisible: false,
      // 添加参数数据对象
      addRuleForm: {
        attr_name: ''
      },
      // 添加参数验证规则对象
      addRuleFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 修改参数对话框默认关闭
      editDialogVisible: false,
      // 修改参数
      editRuleForm: {
        attr_name: ''
      },
      // 添加参数验证规则对象
      editRuleFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
      // 输入框隐藏
      // inputVisible: false,
      // 文本框输入
      // inputValue: ''
    }
  },
  created () {
    // 获取所有的商品分类
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.cateList = res.data
      // console.log(res.data)
    },
    // 级联选择框的数据变化
    handleChange () {
      // console.log(this.selectedCateKeys)
      // 调用参数列表数据
      this.getParamsData()
    },
    // 切换tab标签
    handleClick () {
      // console.log(this.activeName)
      // 调用参数列表数据
      this.getParamsData()
    },
    // 重构获取参数列表数据
    async getParamsData () {
      // 选择的不是三级重置
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
        // 清空动态参数与静态属性的表格清空
        this.manyTableData = []
        this.onlyTableData = []
        return 0
      }
      // 选择的是三级
      // console.log(this.selectedCateKeys)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      // 把attr_vals 字符串分割成字符串数组
      res.data.forEach(item => {
        // attr_vals值为空的时候赋值为空数组
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框的输入
        item.inputValue = ''
      })
      console.log(res.data)
      // 根据tabs名称判断数据挂载对象
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // 添加参数对话框关闭重置
    addDialogClosed () {
      this.$refs.addRuleFormRef.resetFields()
    },
    // 提交添加参数
    addParams () {
      this.$refs.addRuleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addRuleForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) return this.$message.error('获取数据失败')
        this.$message.success('添加参数成功')
        this.addDialogVisible = false
        await this.getParamsData()
      })
    },
    // 修改参数对话框展示
    async showEditDialog (attrId) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { params: { attr_self: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('查询数据失败')
      // 修改数据赋值给editRuleForm
      this.editRuleForm = res.data
      this.editDialogVisible = true
    },
    // 修改对话框重置
    editDialogClosed () {
      this.$refs.editRuleFormRef.resetFields()
    },
    // 点击按钮修改
    editParams () {
      this.$refs.editRuleFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editRuleForm.attr_id}`,
          { attr_name: this.editRuleForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('修改数据失败')
        this.$message.success('修改数据成功')
        await this.getParamsData()
        this.editDialogVisible = false
      })
    },
    // 删除分类
    async showDeleteDialog (attrId1) {
      const resultConfirm = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (resultConfirm !== 'confirm') return this.$message.info('取消了删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId1}`)
      if (res.meta.status !== 200) return this.$message.error('删除数据失败')
      this.$message.success('删除数据成功')
      // 删除成功后刷新数据列表
      await this.getParamsData()
    },
    // 文本框失去焦点或者摁下enter触发
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        // 输入的内容清空
        row.inputValue = ''
        row.inputVisible = false
        return 0
      }
      // 有内容输入
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 对attr_vals(tag)的操作保存到数据库
    async saveAttrVals (row) {
      // 发起数据情况
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('修改数据失败')
      this.$message.success('修改数据成功')
    },
    // 点击按钮打开输入框
    showInput (row) {
      row.inputVisible = true
      // 获取焦点
      // $nextTick 的作用就是当页面的元素重新渲染后，才会指定回调函数的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除tab标签
    handleClosed (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  // 使用计算属性控制tabs的操作
  computed: {
    // 需要禁用返回true，否则为false
    isBtnDisabled () {
      return this.selectedCateKeys.length !== 3
    },
    // 当前选中的三级分类id
    cateId () {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },
    // 添加对话框的标题
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
